<!-- 硬件报警页面 -->
<template>
	<div class="alarm-hardware">
		<div class="page-region">
			<div class="basic-region">
				<div class="basic-region-left">
					<div class="left-action-box">
						<div class="device-part">
							<a-select
								ref="select"
								v-model:value.trim="mAlgorithmIdList"
								class="select-item"
								style="min-width: 180px; max-width: 285px; margin-right: 12px"
								:options="AIServiceList"
								mode="multiple"
								:class="[mAlgorithmIdList.length && 'active']"
								max-tag-count="responsive"
								placeholder="性能指标"
								@change="handleSearch('mAlgorithmIdList')"
							></a-select>
							<a-select
								ref="select"
								v-model:value.trim="tableAttr.searchObj.boxSerial"
								class="select-item"
								style="min-width: 180px; max-width: 285px"
								:options="boxSerialList"
								:field-names="{ label: 'label', value: 'value' }"
								max-tag-count="responsive"
								placeholder="所属盒子"
								@change="handleSearch()"
							></a-select>
						</div>
						<div class="time-part">
							<ul class="select-list">
								<li
									:key="item.value"
									v-for="(item, index) in presetTime"
									class="select-list-item"
									:class="[activeTimeIndex === index && 'active']"
									@click="changeTime(index, item.value)"
								>
									{{ item.text }}
								</li>
							</ul>
							<a-range-picker
								format="YYYY-MM-DD HH:mm"
								class="range-picker"
								value-format="YYYY-MM-DD HH:mm"
								:value="[createBeginVal, createEndVal]"
								show-time
								:class="[createBeginVal && createBeginVal && 'active']"
								:placeholder="['开始时间', '结束时间']"
								input-read-only
								@calendar-change="changeRangePicker"
							>
								<template #suffixIcon> <clock-circle-outlined></clock-circle-outlined></template
							></a-range-picker>
						</div>
					</div>
				</div>
				<div class="basic-region-right">
					<a-button type="text" @click="PageButtonClick('reset')">
						重置
						<global-svg-icon icon-name="reset" style="margin-right: 10px" width="14px" height="14px"></global-svg-icon>
					</a-button>
				</div>
			</div>
			<div ref="refConfModuleContent" class="content">
				<div class="_container">
					<global-table
						:data-source="tableAttr.data"
						:selected-row-keys="tableAttr.selectedKeys"
						:loading="tableAttr.loading"
						:columns="columns"
						:use-select="true"
						:y-scroll-val="yScroll"
						@sort="sort"
						@selected="(rowKeys: any) => (tableAttr.selectedKeys = rowKeys)"
					>
						<template #alarmValue="{ record }">
							<div class="alarmValue" style="color: #ba3b29">{{ record.alarmValue }}{{ record.alarmType === 1 ? 'GB' : '%' }}</div>
						</template>
						<template #alarmThreshold="{ record }">
							<div>{{ record.alarmThreshold }}{{ record.alarmType === 1 ? 'GB' : '%' }}</div>
						</template>
					</global-table>
					<global-pagination
						:style="{ 'padding-bottom': tableAttr.selectedKeys.length !== 0 ? '45px' : '0px' }"
						:current="tableAttr.current"
						:page-size="tableAttr.pageSize"
						:total="tableAttr.total"
						@change="setTablePagination"
					></global-pagination>
				</div>
				<global-table-batch-operation
					v-model:selected-rows="tableAttr.selectedKeys"
					style="position: absolute; bottom: 0; left: 0; width: 100%"
				>
					<template #Slot-Table-Btns>
						<div class="_button">
							<a-button
								v-if="g6Permission.showBtn('export')"
								type="default"
								:loading="exportLoading"
								style="display: flex; align-items: center; margin-left: 32px"
								@click="PageButtonClick('export')"
							>
								<global-svg-icon
									icon-name="upload-2-line"
									:color="tableAttr.selectedKeys.length !== 0 ? '#fff' : 'rgba(78, 89, 106, 1)'"
									width="16px"
									height="16px"
									style="margin-right: 4px"
								></global-svg-icon>
								<p style="color: aliceblue">导出</p>
							</a-button>
						</div>
					</template>
				</global-table-batch-operation>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="alarm-hardware">
defineOptions({ name: 'AlarmHardware' });
import { onMounted } from 'vue';
import { g6UseTable } from 'glasssix-vue3-hooks';
import { g6Permission } from 'glasssix-utils-ts';
import { arr2Str } from '@/global-utils/base.utils';
import { AlarmCenterAPI } from '../../../api';
// import { TsSelectOptItem } from '../../../type';

import dayjs from 'dayjs';

const { tableAttr, setTableData, setTablePagination } = g6UseTable(AlarmCenterAPI.hardWareList, {
	pageSizeOptions: [10, 20, 50, 100, 200]
});
const columns: TsGlobalType.TsTableColumn[] = [
	{ dataIndex: 'performanceName', title: '性能指标', width: 214, ellipsis: true },
	{ dataIndex: 'alarmThreshold', title: '报警阈值', custom: true, width: 214, ellipsis: true },
	{ dataIndex: 'alarmValue', title: '报警值', width: 214, custom: true, ellipsis: true },
	{ dataIndex: 'boxName', title: '所属盒子', custom: true, ellipsis: true },
	{ dataIndex: 'createTime', title: '时间', width: 214, sorter: true, ellipsis: true }
];

/**
 * -----------------------搜索-----------------------
 */
// AI服务下拉数据
const mAlgorithmIdList = ref<string[]>([]);
// const AIServiceList = ref<TsSelectOptItem[]>([]);
// const getAIServiceList = async (): Promise<void> => {
// let { data } = await AlarmCenterAPI.getType();
// AIServiceList.value = data;
const AIServiceList = [
	{
		value: 1,
		label: '存储空间'
	},
	{
		value: 2,
		label: 'CPU利用率'
	},
	{
		value: 3,
		label: '内存利用率'
	},
	{
		value: 4,
		label: 'NPU利用率'
	}
];

// 所属盒子下拉数据
const boxSerialList = ref<Record<string, string>[]>([]);
const getBoxSerialList = async (): Promise<void> => {
	let { data } = await AlarmCenterAPI.getBox();
	boxSerialList.value = data;
};

// 回显页面的
const cameraTreeList = ref([]);

// 时间过滤
const createBeginVal = ref<any>();
const createEndVal = ref<any>();

// 预设时间段
const presetTime = ref<any>([
	{
		text: '今日',
		value: 1
	},
	{
		text: '近7天',
		value: 7
	},
	{
		text: '近30天',
		value: 30
	}
]);
const activeTimeIndex = ref<number>(0);

// 查询
const handleSearch = (key?: string): void => {
	switch (key) {
		case 'mAlgorithmIdList':
			tableAttr.searchObj.alarmTypeS = arr2Str(mAlgorithmIdList.value);

			break;

		default:
			break;
	}

	setTableData(true);
};

const yScroll = computed(() => {
	return tableAttr.selectedKeys.length !== 0 ? 515 : 560;
});

/* ------------------- 处理时间选择逻辑 ------------------ */

// 根据传入的天数，获取以当前时间基准的时间范围
const GetTimeRange = (day: number, init: boolean = true): void => {
	const startTime = dayjs()
		.subtract(day - 1, 'days')
		.startOf('day')
		.format('YYYY-MM-DD HH:mm:ss');
	const endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');
	tableAttr.searchObj.startTime = startTime;
	tableAttr.searchObj.endTime = endTime;
	createBeginVal.value = undefined;
	createEndVal.value = undefined;
	tableAttr.current = 1;
	if (init) {
		handleSearch();
	}
};
const changeRangePicker = (dates: any, date: string[]): void => {
	activeTimeIndex.value = -1;

	if (date && date.length) {
		if (date[0] !== '') {
			tableAttr.searchObj.startTime = `${date[0]}:00`;

			createBeginVal.value = `${date[0]}`;
		}
		if (date[1] !== '') {
			tableAttr.searchObj.endTime = `${date[1]}:59`;
			createEndVal.value = `${date[1]}`;
		}
		if (date[0] === '' && date[1] === '') {
			activeTimeIndex.value = 0;
			GetTimeRange(7);

			tableAttr.searchObj.startTime = undefined;
			tableAttr.searchObj.endTime = undefined;
			createBeginVal.value = undefined;
			createEndVal.value = undefined;
		}

		tableAttr.current = 1;
		handleSearch();
	}
};

const changeTime = (index: number, day: number): void => {
	// 如果是同一天不搜索
	if (index === activeTimeIndex.value) {
		return;
	}
	activeTimeIndex.value = index;

	GetTimeRange(day);
};
// 重置
const reset = (): void => {
	tableAttr.searchObj = {};
	mAlgorithmIdList.value = [];
	cameraTreeList.value = [];
	activeTimeIndex.value = 0;
	createBeginVal.value = '';
	createEndVal.value = '';
	GetTimeRange(1, false);

	setTableData(true);
};

// 排序
const sort = (val: any): void => {
	console.log('排序：', val);
	tableAttr.searchObj.timeSort = val.order;
	setTableData(true);
};

const exportLoading = ref<boolean>(false);
const handleExport = async (): Promise<void> => {
	exportLoading.value = true;
	try {
		const res: TsRes = await AlarmCenterAPI.exportHardWare(tableAttr.selectedKeys.toString());
		const file = res.data;
		if (res.code === 0) {
			const blob = new Blob([file?.data]);

			const downUrl = window.URL.createObjectURL(blob);

			const a = document.createElement('a');
			a.href = downUrl || '';

			// ${getFileSuffix(data.image)}
			const fileName = file?.title.split('filename=')[1];
			console.log('fileName:', decodeURIComponent(fileName));

			a.download = decodeURIComponent(fileName);
			a.click();
			a.remove();
			tableAttr.selectedKeys = [];
			exportLoading.value = false;
		}
	} catch (error) {
		console.log('error', error);
	}
};

const PageButtonClick = (code: string): void => {
	switch (code) {
		case 'reset':
			reset();
			break;
		case 'export':
			handleExport();
			break;

		default:
			break;
	}
};

/* ------------------- 结束 ------------------ */

/**
 * 选中的列表
 */
// 列表数据

const init = (): void => {
	tableAttr.searchObj.timeSort = 'desc';

	// getAIServiceList();
	getBoxSerialList();
	GetTimeRange(1, false);
	setTableData();
};
const refConfModuleContent = ref(null);
onMounted(() => {
	init();
});
</script>

<style lang="less" scoped>
.alarm-hardware {
	// height: 100%;
	margin-right: 32px;

	.page-region {
		// overflow: scroll;
		width: 100%;
		height: calc(100vh - 36px - 24px - 30px - 20px);
		padding: 24px 0;

		.basic-region {
			display: flex;
			justify-content: space-between;

			.basic-region-left {
				display: grid;
				grid-auto-flow: column;
				grid-column-gap: 32px;
				align-items: center;

				.left-action-box {
					display: flex;

					.select-item {
						width: 180px;

						&.active {
							width: 285px;
						}
					}

					.range-picker {
						width: 216px;
						flex-shrink: 0;

						&.active {
							width: 308px;
						}
					}

					.device-part {
						margin-right: 32px;

						:deep(.ant-select) {
							.ant-select-selector {
								height: 36px !important;
							}
						}
					}

					.time-part {
						display: flex;

						.select-list {
							display: flex;
							// width: 280px;
							height: 36px;
							margin: 0 8px 0 0;
							border: 1px solid @mask02;
							border-radius: 6px;
							padding: 3px 0;
							font-size: 14px;
							line-height: 22px;
							color: @text02;
							flex-shrink: 0;

							.select-list-item {
								position: relative;
								width: 87px;
								margin: 0 3px;
								border-radius: 4px;
								padding: 3px 0;
								text-align: center;
								// line-height: 36px;
								cursor: pointer;

								&:hover {
									color: @text02;
									background: @mask03;
								}

								&.active {
									color: @text01;
									background: @primary01;
								}
								// 分割线
								&::after {
									position: absolute;
									top: 50%;
									right: -6px;
									width: 1px;
									height: 14px;
									margin-right: 3px;
									background: @borderColor02;
									transform: translateY(-50%);
									content: '';
								}

								&:last-child {
									&::after {
										display: none;
									}
								}
							}
						}
					}
				}
			}

			.basic-region-right {
				display: grid;
				padding: 8px 16px;
				grid-auto-flow: column;
				grid-column-gap: 8px;
				direction: rtl; // 用来设置文本、表列水平溢出的方向。 rtl 表示从右到左， ltr 表示从左到右
				.reset {
					display: flex;
					flex-direction: column;
					justify-content: center;
					color: @text03;
					cursor: pointer;
				}

				button {
					margin-left: 16px;
				}
			}
		}

		.content {
			height: calc(100% - 76px - 1px - 10px);
			padding: 20px 0;

			._container {
				display: flex;
				height: 100%;
				height: calc(100vh - 76px - 44px - 160px);
				padding: 20px 0 0;
				flex-direction: column;
				justify-content: space-between;

				.alarmValue {
					color: @danger01;
				}
			}
		}

		.checkbox-card {
			width: 100%;
			// position: relative;
			height: 100%;
			margin-top: 20px;

			:deep(.ant-checkbox) .ant-checkbox-input {
				opacity: 1 !important;
			}

			.ant-checkbox-group {
				cursor: default !important;
			}

			.ant-checkbox {
				.ant-checkbox-inner {
					border-color: @borderColor02 !important;
					background: @white !important;
				}
			}

			.card-wrap {
				// overflow: auto;
				// overflow-y: scroll;
				// width: calc(100vw - var(--side-width) - 98px);
				width: 100%;
				height: 100%;
				flex: 1;

				.ant-spin-nested-loading {
					position: absolute;
					top: 12px;
					width: 100%;
					height: 100%;

					.ant-spin-dot {
						margin: 0;
					}
				}

				:deep(.ant-checkbox-inner) {
					border-color: rgba(217, 217, 219, 1) !important;
					background-color: @white !important;
				}

				:deep(.ant-checkbox-checked) {
					.ant-checkbox-inner {
						background: @primary01;
					}
				}

				.card-list {
					// flex-wrap: wrap;
					display: grid;
					// display: flex;
					overflow: hidden;
					// width: calc(100vw - var(--side-width) - 9px);
					width: 100%;
					height: 100%;
					padding-right: 32px;
					grid-template-columns: repeat(8, 1fr);
					grid-template-rows: repeat(2, 1fr);
					grid-column-gap: 20px;
					/* stylelint-disable-next-line declaration-block-no-redundant-longhand-properties */
					grid-row-gap: 20px;

					.lastLine {
						margin-right: 0;
					}

					.card-list-item {
						position: relative;
						height: 220px;
						border: 1px solid transparent;
						border-radius: 6px;
						padding: 4px 6px;
						cursor: pointer;

						.img-wrap {
							width: 100%;
							height: 114px;

							> img {
								width: 100%;
								height: 100%;
								object-fit: cover;
								border-radius: 4px;
							}
						}

						.info-box {
							overflow: hidden; /* 隐藏超出容器的内容 */
							white-space: nowrap; /* 防止换行 */
							text-overflow: ellipsis; /* 当文字超出容器时显示省略号 */
							color: @text03;

							.ai-item {
								display: flex;
								margin-top: 6px;
								font-size: 12px;
								color: @text01;
								justify-content: space-between;

								.ai-alarm-name {
									border-radius: 4px;
									padding: 0 6px;
									font-family: 'Alimama FangYuanTi VF';
									line-height: 20px;
									background: @secondary03;
									text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
								}

								.sence-name {
									line-height: 20px;
								}
							}

							.info-item {
								line-height: 20px;
								color: @text03;
							}

							.time-item {
								color: @text04;
							}
						}

						.tag {
							margin-left: auto;
							border: 1px solid rgba(0, 0, 0, 0.12);
							border-radius: 4px;
							padding: 0 6px;
							font-size: 12px;
							white-space: nowrap;
							color: #d67900;
							background: rgba(245, 151, 0, 0.12);
						}

						.right-top {
							position: absolute;
							top: 6px;
							right: 8px;

							.ant-checkbox-inner {
								background: #fff !important;
							}
						}

						&:hover,
						&.checked {
							border: 1px solid #374b79;
							// background-color: #fff;
							// box-shadow:
							// 	0 2px 8px 0 rgba(37, 37, 45, 0.14),
							// 	0 1px 3px 0 rgba(37, 37, 45, 0.14);
							border-radius: 8px;
							background: radial-gradient(66.29% 107.13% at 0% 0%, rgba(38, 62, 131, 0.12) 0%, rgba(217, 217, 217, 0.02) 100%), #0f224e;
							box-shadow: 0 3px 16px 0 rgba(0, 0, 0, 0.25);

							.right-top {
								display: block !important;
							}

							&::before {
								position: absolute;
								top: 0;
								left: 0;
								width: 100%;
								height: 100%;
								content: '';
								// background-color: rgba(0, 0, 0, 0.08);
							}
						}
					}
				}
			}

			.suspend {
				box-sizing: content-box;
				position: absolute;
				bottom: 0;
				left: 0;
				z-index: 9;
				width: 100%;
				border-top: 1px solid @borderColor01;
				border-bottom-right-radius: 8px;
				border-bottom-left-radius: 8px;
				background: @background02;
				box-shadow:
					0 -1px 3px rgba(37, 37, 45, 0.14),
					0 -2px 8px rgba(37, 37, 45, 0.14);

				.suspend-operate {
					display: flex;
					align-items: center;
					height: 48px;
					border-bottom: 1px solid @borderColor01;
					padding-left: 24px;

					.suspend-operate-select {
						display: flex;
						align-items: center;
						padding-right: 24px;

						:deep(.ant-checkbox-wrapper) {
							span {
								color: @text01 !important;
							}
						}

						p {
							font-size: 14px;
							font-weight: 400;
							color: @primary01;
						}

						span {
							display: block;
							width: 1px;
							height: 20px;
							margin: 0 24px;
							background: #d9d9db;
						}
					}

					.export-line {
						display: block;
						width: 1px;
						height: 38px;
						margin: 0 24px;
						background: @borderColor02;
					}

					.suspend-operate-btns {
						display: flex;
						height: 100%;
						// border-left: 1px solid @borderColor02;
						padding-left: 24px;
						align-items: center;
						gap: 0 12px;
					}
				}

				.suspend-pagination {
					display: flex;
					height: 48px;
					padding: 0 24px;
					color: @text01;
					align-items: center;
					box-shadow: 0 -1px 8px 0 rgba(0, 0, 0, 0.25);

					.icon-button {
						width: 82px;
						height: 36px;
					}

					.pagination {
						margin: 0 auto;
					}

					.icon-select-button {
						background-color: rgba(0, 0, 0, 0.1);
					}
				}
			}
		}
	}
}
</style>
